package com.zcxy360.sandtable.shiro;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.zcxy360.sandtable.domain.User;
import com.zcxy360.sandtable.service.UserService;

public class RememberMeFilter implements Filter {

	@Autowired
	private UserService userService;

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		Subject subject = SecurityUtils.getSubject();
        if (subject.isRemembered()) {
        	Session session = subject.getSession(false);
        	if(session != null) {
        		session.setTimeout(1000*60*60);
        		if(session.getAttribute("user")==null) {
        			String username = subject.getPrincipal().toString();
        			User user = userService.getUserByUsername(username);
        			if (user != null) {
        				session.setAttribute("user", user);
        			}
        		}
        	}
        }
        chain.doFilter(request, response);
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
